
<style lang='scss'>
.label-modal {
  .ivu-modal {
    top: 20px;
  }
}
.addlabel .newbase-box .ivu-form-item {
    margin-bottom: 15px;
    .ivu-form-item-error-tip{
        padding-top:0;
    }
    .ivu-table th{
        background-color: #dce4ed;
    }

}
.addlabel-title{
    display: block;
    font-size: 13px;
    background-color: #fff;
    padding: 12px 16px;
    border-bottom: 1px solid #ddd;
    margin: 0 -10px 6px -12px;
}

</style>
<template>
	<div class="addlabel">
        <!-- <div class="addlabel-title">
            创建运单
        </div> -->
        <Row>
            <Col span="10" style="padding-right:7px">
                <div class="newbase-box" style="height:310px">
                    <div class="newbase-title">发货信息</div>
                    <div class="margin-top-10 margin-bottom-10">
                        <span class="margin-left-20"><Checkbox v-model="replaceGoods" class="margin-right-5"></Checkbox>退货单</span>
                        <Button class="pull-right margin-right-20" size="small" @click="clearShip">清空发货信息</Button>
                        <Button class="pull-right margin-right-20" size="small" type="primary" @click="goRoute('calculate')">邮编测算
                            <Tooltip content="可以基于邮编测算">
                                <Icon type="md-help-circle" />
                            </Tooltip>
                        </Button>
                    </div>
                    <div>
                        <Form class="clearfix padding-right-15" ref="shipper" :model="fromAddress" :label-width="130" :rules="shipperRules">
                            <Row>
                            <Col span="12">
                                <FormItem prop='contactName' label="发货方" class="relative">
                                    <Input v-model="fromAddress.contactName"  placeholder='请选择' v-if="!showDisa"/>
                                    <div v-else>{{fromAddress.contactName}}</div>
                                    <a v-if="replaceGoods ? false : true" @click="showShippers=true" class="absolute pointer" style="right:-39px;top:0px;z-index:1;">地址簿</a>
                                </FormItem>
                            </Col>
                            <Col span="12" v-if="replaceGoods ? false : true">
                                <FormItem prop='code' label="发货方Code">
                                    <Input v-if="!showDisa" v-model="fromAddress.code" :readonly="fromAddress.id" @on-blur="isDataCode(fromAddress.code)"/>
                                    <div v-else>{{fromAddress.code}}</div>
                                </FormItem>
                            </Col>
                            <Col span="12">
                                <FormItem prop="country" label="国家">
                                    <Select v-model="fromAddress.country" v-if="!showDisa" clearable filterable>
                                        <Option v-for="(item,index) in countryList" :key="index" :value="item.value">{{item.label}}</Option>
                                    </Select>
                                <div v-else>{{fromAddress.country}}</div>
                                </FormItem>
                            </Col>
                            <Col span="12">
                                <FormItem prop="state" label="州">
                                    <div v-if="!showDisa">
                                        <Select v-if="fromAddress.country == 'US'" v-model="fromAddress.state" clearable filterable >
                                            <Option v-for="val in getStateList" :key="val" :value="val">{{val}}</Option>
                                        </Select>
                                        <Input v-else v-model="fromAddress.state"></Input>
                                    </div>
                                    <div v-else>{{fromAddress.state}}</div>
                                </FormItem>
                            </Col>
                            <Col span="12">
                                <FormItem prop="city" label="城市">
                                    <Input v-model="fromAddress.city" v-if="!showDisa"/>
                                    <div v-else>{{fromAddress.city}}</div>
                                </FormItem>
                            </Col>
                            <Col span="12">
                                <FormItem prop="zip" label="邮编">
                                    <Input v-model="fromAddress.zip" v-if="!showDisa"/>
                                    <div v-else>{{fromAddress.zip}}</div>
                                </FormItem>
                            </Col>
                            <Col span="12">
                                <FormItem prop="phone" label="联系电话">
                                    <Input v-model="fromAddress.phone" v-if="!showDisa"/>
                                    <div v-else>{{fromAddress.phone}}</div>
                                </FormItem>
                            </Col>
                            <Col span="12">
                                <FormItem prop="street1" label="详细地址" class="width-100per">
                                    <Input v-model="fromAddress.street1" class="width-100per" v-if="!showDisa"/>
                                    <div v-else>{{fromAddress.street1}}</div>
                                    <Button class="pull-right margin-top-20" v-if="replaceGoods ? false : true" @click="saveReceData">保存到地址薄</Button>
                                </FormItem>
                            </Col>
                            </Row>
                        </Form>
                    </div>
                </div>


                <div class="newbase-box margin-top-15" style="height:320px">
                    <div class="newbase-title">收货信息</div>
                    <div>
                        <Form class="clearfix padding-right-15 margin-top-5" ref="receiver" :model="toAddress" :label-width="120" :rules="receiverRules" >
                            <Row>
                                <Col span="12">
                                <FormItem prop='contactName' label="收货方名称" class="label-formitem relative">
                                    <div v-if="replaceGoods">{{toAddress.contactName}}</div>
                                    <Input v-else v-model="toAddress.contactName"  placeholder='请选择'/>
                                    <a @click="replaceGoods ? showShippers=true : showReceivers=true" class="absolute pointer" style="right:-39px;top:0px;z-index:1">地址簿</a>
                                </FormItem>
                                </Col>
                                <Col span="12">
                                <FormItem prop="country" label="国家">
                                    <div v-if="replaceGoods">{{toAddress.country}}</div>
                                    <Select v-else v-model="toAddress.country" clearable filterable>
                                        <Option v-for="(item,index) in countryList" :key="index" :value="item.value">{{item.label}}</Option>
                                    </Select>
                                </FormItem>
                                </Col>
                                <Col span="24">
                                </Col>
                                <Col span="12">
                                <FormItem prop="state" label="州">
                                    <div v-if="replaceGoods">{{toAddress.state}}</div>
                                    <div v-else>
                                        <Select v-if="toAddress.country == 'US'" v-model="toAddress.state" clearable filterable>
                                            <Option v-for="val in getStateList" :key="val" :value="val">{{val}}</Option>
                                        </Select>
                                        <Input v-else v-model="toAddress.state"></Input>
                                    </div>
                                </FormItem>
                                </Col>
                                <Col span="12">
                                <FormItem prop="city" label="城市">
                                    <div v-if="replaceGoods">{{toAddress.city}}</div>
                                    <Input v-else v-model="toAddress.city" />
                                </FormItem>
                                </Col>
                                <Col span="12">
                                <FormItem prop="zip" label="邮编">
                                    <div v-if="replaceGoods">{{toAddress.zip}}</div>
                                    <Input v-else v-model="toAddress.zip" />
                                </FormItem>
                                </Col>
                                <Col span="12">

                                <FormItem prop="phone" label="联系电话">
                                    <div v-if="replaceGoods">{{toAddress.phone}}</div>
                                    <Input v-else v-model="toAddress.phone" />
                                </FormItem>
                                </Col>
                                <Col span="12">
                                <FormItem prop="street1" label="详细地址1" class="width-100per">
                                    <div v-if="replaceGoods">{{toAddress.street1}}</div>
                                    <Input v-else v-model="toAddress.street1" class="width-100per" />
                                </FormItem>
                                </Col>
                                <Col span="12">
                                <FormItem  label="详细地址2" class="width-100per">
                                    <div v-if="replaceGoods">{{toAddress.street2}}</div>
                                    <Input v-else v-model="toAddress.street2" class="width-100per" />
                                </FormItem>
                                </Col>
                                <Col span="12">
                                <FormItem label="详细地址3" class="width-100per">
                                    <div v-if="replaceGoods">{{toAddress.street3}}</div>
                                    <Input v-else v-model="toAddress.street3" class="width-100per" />

                                </FormItem>
                                </Col>
                                <Col span="24" class="margin-bottom-5">
                                    <Button class="pull-right" v-if="replaceGoods ? false : true" @click="showSaveReceiver=true">保存到地址薄</Button>
                                </Col>
                            </Row>
                        </Form>
                    </div>
                </div>
            </Col>
            <Col span="14" style="padding-left:8px;">
                <div class="newbase-box" style="height:645px;overflow:auto">
                    <div class="newbase-title">包裹信息</div>
                    <div v-if="!replaceGoods" class="margin-top-10 margin-bottom-10">
                        <Checkbox style="margin-left:20px;" class="margin-right-5" v-model="showPack" @on-change="changeShowPack"></Checkbox> 子母单
                        <span v-if="showPack" class="margin-left-20 margin-right-5">包裹 <InputNumber :min="1" v-model="packnumber"></InputNumber></span>
                        <a v-if="showPack" type="info" @click="addPackList">添加包裹</a>
                    </div>
                    <div class="color-error" style="margin-left:20px;margin-top:10px;" span="24">
                        包裹长、宽、高请输入正整数，若输入小数，则自动向上取整；包裹重量保留小数点后两位，超过两位则四舍五入保留两位
                    </div>
                    <div class="margin-15" v-for="(item,index) in packageList" :key="index" style="border-bottom:1px dashed #d1d1d1">
                        <div style="height:35px;" v-if="showPack">
                            <span style="margin-left:105px;font-size:12px;">包裹 : {{index+1}}</span>

                            <Button class="margin-bottom-5 pull-right margin-right-5" size="small" type="primary" @click="showItempack(item.showOnePack,index)">{{item.showOnePack ? '隐藏' : '展开'}}包裹</Button>
                        </div>
                        <Form v-show="item.showOnePack" class="clearfix" :model="parcelData" :labelWidth="105">
                            <Row>
                            <Col span="6">
                                <FormItem label="Reference" >
                                    <Input v-model="item.options.printCustom1"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="PO" >
                                    <Input v-model="item.options.printCustom2"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="Invoice" >
                                    <Input v-model="item.options.printCustom3"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="Department" >
                                    <Input v-model="item.options.printCustom4"></Input>
                                </FormItem>
                            </Col>
                            <Col span="3" class="text-center margin-bottom-10">
                                <div class="margin-bottom-5">长</div>
                                <div>
                                    <InputNumber :min='1' v-model="item.parcel.length" @on-blur="handleSize('parcel',item.parcel.length,index,'length')"/>
                                </div>
                            </Col>
                            <Col span="3" class="text-center">
                                <div class="margin-bottom-5">宽:</div>
                                <div>
                                    <InputNumber :min='1' v-model="item.parcel.width" @on-blur="handleSize('parcel',item.parcel.width,index,'width')"/>
                                </div>
                            </Col>
                            <Col span="5" class="text-center">
                                <div class="margin-bottom-5">高:</div>
                                <div>
                                    <InputNumber :min='1' v-model="item.parcel.height" @on-blur="handleSize('parcel',item.parcel.height,index,'height')"/>
                                    <Select v-model="item.parcel.lengthUnit" class="width-60" clearable filterable>
                                        <Option value="inch">inch</Option>
                                        <Option value="cm">cm</Option>
                                    </Select>
                                </div>
                            </Col>
                            <Col span="7" class="text-center">
                                <div class="margin-bottom-5">包裹重量:</div>
                                <div>
                                    <InputNumber :min='1'  v-model="item.parcel.weight" @on-blur="handleSize('parcel',item.parcel.weight,index,'weight')"/>
                                    <Select  v-model="item.parcel.weightUnit" class="width-60" clearable filterable>
                                        <Option value="oz">oz</Option>
                                        <Option value="lbs">lbs</Option>
                                        <Option value="g">g</Option>
                                    </Select>
                                </div>
                            </Col>
                            <Col span="4" class="text-center">
                                <div class="margin-bottom-5">申报价值:</div>
                                <div>
                                    <Input v-model="item.insurance"></Input>
                                </div>
                            </Col>
                            <Col span="2" class="text-center">
                                <div class="margin-bottom-5">操作:</div>
                                <div>
                                    <a class="color-default" @click="deleteItempack(item.showOnePack,index)"><Icon style="font-size:30px" type="ios-trash-outline" /></a>
                                </div>

                            </Col>
                            <!-- <Col span="12" v-if="replaceGoods ? true : false">
                                <FormItem label="取件方式" >
                                    <Select v-model="item.options.dropoffType" clearable filterable>
                                        <Option value="REGULAR_PICKUP">上门取件</Option>
                                        <Option value="SCHEDULED_PICKUP">SCHEDULED_PICKUP</Option>
                                        <Option value="RETAIL_LOCATION">RETAIL_LOCATION</Option>
                                        <Option value="STATION">STATION</Option>
                                        <Option value="DROP_BOX">DROP_BOX</Option>
                                    </Select>
                                </FormItem>
                            </Col> -->
                            </Row>
                        </Form>

                    </div>

                </div>
            </Col>
        </Row>


        <!-- 清关信息和附件信息 -->
        <div class="newbase-box margin-top-15" v-if="!showPack && fromAddress.country!=toAddress.country && fromAddress.country && toAddress.country">
            <div class="newbase-title">清关信息</div>
            <div>
                <Form class="clearfix padding-right-15 margin-top-5" :label-width="160"  ref='customsData' :model='customsItems'>
                    <Row>
                        <Col span="6">
                        <FormItem label="Description" prop="description" :rules="requireRule">
                            <Input v-model="customsItems.description"  />
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="Quantity" prop="quantity" :rules="requireRule">
                            <Input v-model="customsItems.quantity"  />
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="Weight" prop="weight" :rules="requireRule">
                            <Input v-model="customsItems.weight"  />
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="Weight_units" prop="weightUnits" :rules="requireRule">
                            <Select v-model="customsItems.weightUnits" clearable filterable>
                                <Option value="lbs">lbs</Option>
                                <Option value="oz">oz</Option>
                                <Option value="g">g</Option>
                            </Select>
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="Currency" prop="currency" :rules="requireRule">
                            <Select v-model="customsItems.currency" clearable filterable>
                                <Option v-for="(item,index) in  getCurrencyList" :key="index" :value="item">{{item}}</Option>
                            </Select>
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="Origin_Country" prop="originCountry" :rules="requireRule">
                            <!-- <Input v-model="customsItems.originCountry"  /> -->
                            <Select v-model="customsItems.originCountry" clearable filterable>
                                <Option v-for="(item,index) in countryList" :key="index" :value="item.value">{{item.label}}</Option>
                            </Select>
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="UnitPrice" prop="unitPrice" :rules="requireRule">
                            <Input v-model="customsItems.unitPrice"  />
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="Value" prop="value" :rules="requireRule">
                            <Input v-model="customsItems.value"  />
                        </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        </div>

        <div class="newbase-box margin-top-15">
            <div class="newbase-title">附加信息</div>
            <div>
                <Form class="clearfix padding-right-15 margin-top-5" :label-width="160"  ref='otherData' :model='otherData'>
                    <Row>
                        <Col span="6">
                        <FormItem label="关联单号" class="width-100per" prop="reference"  :rules="requireRule">
                            <Input v-model="otherData.reference" clearable placeholder="可填写源系统相关联的订单、包裹号" >
                                <template #prefix>
                                    <Tooltip content="可通过关联单号查询到对应单据">
                                        <Icon type="md-help-circle" />
                                    </Tooltip>
                                </template>
                            </Input>
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="签名服务">
                            <Select v-model="otherData.deliveryConfirmation" clearable filterable>
                                <Option v-for="(item,index) in  signServeList" :key="index" :value="item.value">{{item.label}}</Option>
                            </Select>
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="运营商" prop='carrier' :rules='carrierRule'>
                            <Select v-model="otherData.carrier" @on-change="changeCode(otherData.carrier)" clearable filterable>
                                <Option v-for="(item,index) in  carrierList" :key="index" :value="item.attach.carrierGroupCode">{{item.label}}</Option>
                            </Select>
                        </FormItem>
                        </Col>
                        <Col span="6">
                        <FormItem label="运营商服务">
                            <Select v-model="otherData.serviceCode" clearable filterable>
                                <Option v-for="(item,index) in  carrierServeList" :key="index" :value="item.attach.code">{{item.label}}</Option>
                            </Select>
                        </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div class="text-right padding-right-15 padding-bottom-5">
                    <Button type="primary" @click="hanldeCalculate" >服务测算</Button>
                </div>
            </div>
        </div>



		<section class="bg-fff shadow margin-top-15">

            <div class="margin-bottom-10 padding-top-10" v-for="(item,index) in calculShipments" :key="index">
                <div style="height:40px;">
                    <span style="margin-left:105px;font-size:12px;">包裹 : {{index+1}}</span>
                    <Button class="margin-bottom-5 pull-right margin-right-20" size="small" type="success" @click="showItemTable(item,item.showOneTable,index)">{{item.showOneTable ? '隐藏' : '展开'}}包裹</Button>
                </div>
                <div v-if="item.showOneTable && index==0" style="margin:0 20px;">
                    <Table
                    :columns="calculcolumns"
                    size="small"
                    :data="item.rates"
                    @on-current-change="getCalculCurrentRow"
                    border
                    highlight-row
                ></Table>
                </div>
                <div v-if="item.showOneTable && index>0" style="margin:0 20px;">
                    <Table
                    :columns="calculcolumns2"
                    size="small"
                    :data="item.rates"
                    border
                    highlight-row
                ></Table>
                </div>
            </div>
            <div class="text-right padding-20" v-if="showSubmit">
                <Button type="primary" @click="submit" >获取运单</Button>
                <!-- <Button class="width-20per" @click="cancel">取消</Button> -->
            </div>
		</section>




		<Modal class="label-modal" v-model="showShippers" title="发货方地址" :width='800' @on-ok='confirmAddress(replaceGoods ? false : true)' @on-cancel='searchData={}'>
			<div class="width-50per margin-bottom-15 relative" @keyup.enter='getAddressList(replaceGoods ? false : true)'>
				<Input placeholder="输入发货方名称搜索" v-model="searchData.shipper" />
				<Icon class="absolute pointer" :size="22" type="ios-search" @click.native="getAddressList(replaceGoods ? false : true)" style="padding:5px 7px;right:0;top:0;background-color:#2d8cf0;color:#fff;" ></Icon>
			</div>

			<stable v-if="showShippers" :formData='{search:{EQ_active:1}}' ref="shipperTable" url='/api/jwt/spl/shipper/query' highlight-row @on-current-change='getCurrentRow' :columns='shipperTabel' />
		</Modal>
		<Modal class="label-modal" v-model="showReceivers" title="收货方地址" :width='800' @on-ok='confirmAddress(replaceGoods ? true : false)' @on-cancel='searchData={}'>
			<div class="width-50per margin-bottom-15 relative" @keyup.enter='getAddressList(replaceGoods ? true : false)'>
				<Input placeholder="输入收货方名称搜索" v-model="searchData.receiver" />
				<Icon class="absolute pointer" :size="22" type="ios-search" @click.native="getAddressList(replaceGoods ? true : false)" style="padding:5px 7px;right:0;top:0;background-color:#2d8cf0;color:#fff;" ></Icon>
			</div>
			<stable v-if="showReceivers" ref="receiverTabel"  url='/api/jwt/spl/receiver/query' highlight-row @on-current-change='getCurrentRow' :columns='receiverTabel' />
		</Modal>
		<Modal v-model="showSaveShipper" title="保存地址" @on-ok='updateShipper'>
            <div class="text-center padding-10">
                是否将地址保存到地址簿
            </div>
		</Modal>
		<Modal v-model="showSaveReceiver" title="保存地址" @on-ok='updateReceiver'>
            <div class="text-center padding-10">
                是否将地址保存到地址簿
            </div>
		</Modal>

        <!-- 全局弹框 -->
		<compModal
			v-model="modalProps.show"
			v-bind="modalProps"
            @on-close="closemodalprops"
		>
            <component :is="modalProps.component" v-bind="modalProps" v-on="modalProps.on" ></component>
        </compModal>
        <!-- 新增loading -->
        <Spin size="large" fix v-if="loading"></Spin>
	</div>
</template>

<script>
import {
	HttpCreateLabel,
    HttpCalculateLabel,
	HttpShipperList,
	HttpSaveShipper,
	HttpSaveReceiver,
    HttpReceiverList,
    HttpOrderCarrierList,
    HttpOrderCarrierServiceList,
    HttpGetServiceProductList,
    HttpGetProductByOrgLabel,
    HttpCountryList,
} from '@/service/api/views';
import calculate from './calculate';
import stable from './stable';
import compAlertRate from './alertrate';
import {mapGetters,mapState} from 'vuex'
import { h,resolveComponent } from 'vue'
export default {
	components: {
		calculate,
		stable,
        compAlertRate
	},
	data() {
		return {
            modalProps:{},
            showDisa:false,
            replaceGoods:false,
            value1:'',
            packnumber:1,
            showPack:false,
            packageList:[],
            showSubmit:false,
            calculShipments:[],
			fromAddress: {
				country: '',
				state: '',
				city: '',
				zip: '',
				contactName: '',
				phone: '',
				street1: '',
				code: '',
			},
			toAddress: {
				contactName: '',
				country: '',
				state: '',
				city: '',
				zip: '',
				phone: '',
				street1: '',
                code:'',
			},
			parcelData: {
				parcelLengthUnit: 'inch',
			},
			otherData: {
				carrier: '',
				serviceCode: '',
                reference: '',
                remark:'',
			},
            customsItems:{
                description:'',
                originCountry:'',
                quantity:'',
                value:'',
                weight:'',
                weightUnits:'',
                currency:'',
                unitPrice:'',
            },
            carrier: '',
			serviceCode: '',
			currentRow: {},
            calculcurrentRow:{},
			shipperRules: {},
			receiverRules: {},
			carrierRule: null,
            customsRule:{},
			loading: false,
			isCalculate: false,
			showShippers: false,
			showReceivers: false,
			showSaveShipper: false,
			showSaveReceiver: false,
			searchData: {
				shipper: '',
				receiver: '',
			},
			ruleNumber: [
				{
					required: true,
					message: '该信息不能为空,请填写信息',
					trigger: 'blur',
					type: 'number',
				},
			],
			shipperTabel: [
				{
					title: 'NO',
					type: 'index',
					width: 60,
				},
				{
					title: '发货方名称',
					key: 'contactName',
				},
				{
					title: '地址',
					key: 'countrycode',
					render(h, { row }) {
						let address = `${row.countrycode} ${row.state}  ${row.city}  ${row.addressLine1 || ''}`;
						return h('span', address);
					},
				},
			],
			receiverTabel: [
				{
					title: 'NO',
					type: 'index',
					width: 60,
				},
				{
					title: '收货方名称',
					key: 'contactName',
				},
				{
					title: '地址',
					key: 'countrycode',
					render(h, { row }) {
						let address = `${row.countrycode} ${row.state}  ${row.city}  ${row.addressLine1 || ''}`;
						return h('span', address);
					},
				},
			],
			requireRule: [
				{
					required: true,
					message: '该信息不能为空,请填写'
				},
			],
            carrierList:[],
            countryList:[],
            carrierServeList:[],
            signServeList: [
                {label:'NO_SIGNATURE(无需签名)',value:'NO_SIGNATURE'},
                {label:'SIGNATURE(需要签名)',value:'SIGNATURE'},
                {label:'ADULT_SIGNATURE(成人签名)',value:'ADULT_SIGNATURE'},
                {label:'INDIRECT_SIGNATURE(间接签名)',value:'INDIRECT_SIGNATURE'},
            ],
		};
	},
	created() {
		this.shipperRules = this.validate(this.fromAddress);
		this.receiverRules = this.validate(this.toAddress);
		this.carrierRule = [
			{
				validator: (rule, value, callback) => {
					if (this.otherData.serviceCode) {
						if (value) {
							callback();
						} else {
							callback(new Error('该信息不能为空,请填写'));
						}
					} else {
						callback();
					}
				},
			},
		];
        // 清关信息
        this.customsRule = this.validate(this.customsItems);
        this.addPackList()
        this.getCarrier()
        this.getAllCountry()
	},
	computed:{
		...mapGetters('common',['getStateList','getCurrencyList']),
        ...mapGetters('dictionary', ['getCountryList']),
        calculcolumns(){
            return [
				{
					title: '选择',
					width: 70,
					align: 'center',
					render: (h, { row, index }) => {
						const calculcurrentRow = this.calculcurrentRow;

                        return h(resolveComponent("Radio"),
                            {
                                modelValue: calculcurrentRow.index == index,

                            }
                        );
					},
				},
				{
					title: '运营服务',
					key: 'carrier',
					render(h, { row }) {
                        return h('div', `${row.carrier}  ${row.serviceCode}`);
					},
				},
				{
					title: '折扣价格',
					key: 'conversionTotalRate',
					render:(h, { row })=>{
                        return <div>
							<a onClick={this.handleRate.bind(this, row)}>{row.conversionTotalRate}{row.currency}</a>
						</div>
					},
				},
				{
					title: '是否家庭地址',
					key: 'residential',
					render(h, { row }) {
						return h('div', row.residential == 1 ? '是' : '否');
					},
				},
			];
        },
        calculcolumns2(){
            return [
            {
					title: '选择',
					width: 70,
					align: 'center',
					render: (h, { row, index }) => {
                        return '--'
					},
				},
				{
					title: '运营服务',
					key: 'carrier',
					render(h, { row }) {
                        return h('div', `${row.carrier}  ${row.serviceCode}`);
					},
				},
				{
					title: '折扣价格',
					key: 'conversionTotalRate',
					render:(h, { row })=>{
                        return <div>
							<a onClick={this.handleRate.bind(this, row)}>{row.conversionTotalRate}{row.currency}</a>
						</div>
					},
				},
				{
					title: '是否家庭地址',
					key: 'residential',
					render(h, { row }) {
						return h('div', row.residential == 1 ? '是' : '否');
					},
				},
			];
        }
	},
	methods: {
        // 点击折扣价格
		handleRate(row){
            console.log(row,'ddd')
			this.modalProps = {
				show:true,
				title:'查看',
				width: '600',
                component: 'compAlertRate',
				dataList:row.rateItems,
				showFooter:false,
			}
		},
        getCarrier(){
            // HttpOrderCarrierList()
            HttpGetProductByOrgLabel({customerId: global.SYSID}).then(res=>{
                // this.carrierList = res.data
                this.carrierList = res.data.map(item=>{
                    return {value: item.id, label: item.carrier_group_code, attach: item}
                })
            })
        },
        getAllCountry(){
            HttpCountryList({limit: 9999}).then(res=>{
                this.countryList = res.data.map(item=>{
                    return {value: item.code, label: `${item.name_en}(${item.name})`, attach: {
                        nameEn: item.name_en,
                        name: item.name,
                        id: item.id,
                    }}
                })
            })
        },
        showItempack(val,index){
            val = !val
            this.packageList[index].showOnePack = val
            // this.$set(this.packageList[index].showOnePack,index,val)
        },
        showItemTable(val,tag,index){
            tag = !tag
            this.calculShipments[index].showOneTable = tag
            // this.$set(this.calculShipments,index,{...val,showOneTable:tag})
            // console.log(this.calculShipments)
        },
        deleteItempack(val,index){
            if(this.packageList.length ==1 ){
                this.$Message.error({
                    content: '包裹数量最少为1！',
                    duration: 30,
                    closable: true
                });
                return
            }
            this.packageList.splice(index,1);
            this.packnumber = this.packageList.length
        },
        addPackList(){
            let packageArr = [];
            let datajson = {
                showOnePack:true,
                insurance:'',
                remark:'',
                options:{
                    printCustom1Code: "REF",
                    printCustom1: "",
                    printCustom2Code: "PO",
                    printCustom2: "",
                    printCustom3Code: "INV",
                    printCustom3: "",
                    printCustom4Code: "DP",
                    printCustom4: "",
                    deliveryConfirmation: "",
                },
                parcel:{
                    lengthUnit:'inch',
                    weightUnit:'lbs',
                    weight:'',
                    length:'',
                    width:'',
                    height:'',
                },
            }
            // this.packageList.length = this.packnumber;
            for(let i=0;i<this.packnumber;i++){
                packageArr.push(JSON.parse(JSON.stringify(datajson)));
            }
            this.packageList = packageArr.concat()
            // console.log(packageArr,'packageArr')
            // this.packageList.push(JSON.parse(JSON.stringify(datajson)))
        },
        isDataCode(value){
            if(value){
                HttpShipperList({
                    "search[EQ_code]":value
                }).then(res=>{
                    // console.log(res)
                    if(res.data.totalElements>0){
                        this.$Message.error('code系统已存在，请从地址薄选择');
                        this.fromAddress.code = ''
                        return;
                    }
                },err=>{
                    this.$Message.error(err.message);
                })
            }
        },
        saveReceData(){
            if(this.fromAddress.code){
                HttpShipperList({
                    "search[EQ_code]":this.fromAddress.code
                }).then(res=>{
                    // console.log(res)
                    if(res.data.totalElements>0){
                        this.$Message.error('code系统已存在，请从地址薄选择');
                        this.fromAddress.code = ''
                        return;
                    }else{
                        this.showSaveShipper=true;
                    }
                },err=>{
                    this.$Message.error(err.message);
                })

            }
        },
        clearShip(){
            this.fromAddress = {
				country: '',
				state: '',
				city: '',
				zip: '',
				contactName: '',
				phone: '',
				street1: '',
				code: '',
            };
            this.showDisa = false;
        },
        changeCode(val){
            this.otherData.serviceCode = ''
            console.log(val)
            if(val){
                let carrierGroupId = this.carrierList.filter(item => item.attach.carrierGroupCode == val)[0].value;
                HttpGetServiceProductList({
                    contextId:global.SYSID,
                    carrierGroupId: carrierGroupId,
                    orgId: global.SYSID,
                }).then(res=>{
                    this.carrierServeList = res.data.map(item => {
                        return {
                            value: item.id,
                            label: item.code,
                            attach:item,
                        };
                    });
                })
            }
        },
		handleSize(key, val, index,type) {
			val = val || 0
			val = type === 'weight' ? val.toFixed(2) : Math.ceil(val);
            this.packageList[index][key][type] = val
			// this.$set(type, this.packageList[index][key], `${val}`);
		},
		validate(fields, rule) {
			const rules = {};
			rule = rule || {
				required: true,
				message: '该信息不能为空,请填写',
				trigger: 'blur',
			};
			Object.keys(fields).forEach(key => {
				rules[key] = rule;
			});
			return rules;
		},
		getCurrentRow(currentRow) {
			this.currentRow = currentRow;
		},
        getCalculCurrentRow(currentRow){
            console.log(currentRow)
            this.calculcurrentRow = currentRow;
            this.carrier = currentRow.carrier;
            // this.changeCode(currentRow.carrier)
            this.serviceCode = currentRow.serviceCode;
        },
		getAddressList(isShipper) {
			if (isShipper) {
				this.$refs.shipperTable.updateList({
					search: { EQ_active: 1, CN_contactName: this.searchData.shipper || '' },
				});
			} else {
				this.$refs.receiverTabel.updateList({ search: { CN_contactName: this.searchData.receiver || '' } });
			}
		},
		confirmAddress(isShipper) {
            const currentRow = this.currentRow;
			if (isShipper) {
				this.fromAddress = {
					id: currentRow['id'],
					contactName: currentRow['contactName'],
					code: currentRow['code'],
					country: currentRow['countrycode'],
					state: currentRow['state'],
					city: currentRow['city'],
					zip: currentRow['zipcode'],
					phone: currentRow['contactPhone'],
					street1: currentRow['addressLine1'],
				};
			} else {
				this.toAddress = {
					id: currentRow['id'],
					contactName: currentRow['contactName'],
					country: currentRow['countrycode'],
					state: currentRow['state'],
					city: currentRow['city'],
					zip: currentRow['zipcode'],
					phone: currentRow['contactPhone'],
					street1: currentRow['addressLine1'],
					street2: currentRow['addressLine2'],
					street3: currentRow['addressLine3'],
                    code: currentRow['code'],
				};
			}
            this.currentRow = {};
            if(currentRow.id){
                if(this.replaceGoods){
                    this.showDisa = false
                }else{
                    this.showDisa = true;
                }
                this.showShippers = false;
                this.showReceivers = false;
            }
		},
		goRoute(name) {
			this.$router.push({
				name,
			});
		},

		async validator() {
			let shipper = await this.$refs['shipper'].validate();
			let receiver = await this.$refs['receiver'].validate();
			let other = await this.$refs['otherData'].validate();

			return shipper && receiver && other;
		},

		async updateShipper() {
			let valid = await this.$refs['shipper'].validate();
			if (!valid) return;
			const data = this.fromAddress;
			let formdata = {
				contactName: data['contactName'],
				code: data['code'],
				countrycode: data['country'],
				state: data['state'],
				city: data['city'],
				zipcode: data['zip'],
				contactPhone: data['phone'],
				addressLine1: data['street1'],
			};
			if (data.id) {
				formdata.id = data.id;
			}
			const response = await HttpSaveShipper(formdata).catch(res => {
				this.$Message.error(res.message || 'error');
			});
			if (response) {
				this.$Message.success(response.message || 'success');
			}
		},
		async updateReceiver() {
			let valid = await this.$refs['receiver'].validate();
			if (!valid) return;
			const data = this.toAddress;
			let formdata = {
				contactName: data['contactName'],
				countrycode: data['country'],
				state: data['state'],
				city: data['city'],
				zipcode: data['zip'],
				contactPhone: data['phone'],
				addressLine1: data['street1'],
				addressLine2: data['street2'],
				addressLine3: data['street3'],
			};
			if (data.id) {
				formdata.id = data.id;
			}
			const response = await HttpSaveReceiver(formdata).catch(res => {
				this.$Message.error(res.message || 'error');
			});
			if (response) {
				this.$Message.success(response.message || 'success');
			}
		},
        beforeValid(type){
            let flag = false;
            let packNumFlag = false;
            let retuFalg = false;
            for(let i=0;i<this.packageList.length;i++){
                if(this.packageList[i].options.printCustom1 || this.packageList[i].options.printCustom2 || this.packageList[i].options.printCustom3 || this.packageList[i].options.printCustom4){
                    flag = true;
                }
                if(!this.packageList[i].parcel.length || !this.packageList[i].parcel.width || !this.packageList[i].parcel.height || !this.packageList[i].parcel.weight){
                    packNumFlag = true;
                }
            }
            if(flag && !this.otherData.carrier && type=='submit'){
                this.$Message.error('请选择运营商!');
                return retuFalg=true;
            }
            if(packNumFlag){
                this.$Message.error('请填写包裹信息!');
                return retuFalg =true;
            }
            let optionsFlag = {};
            if(this.otherData.carrier == 'FedEx'){
                optionsFlag = {
                    printCustom1Code: "REF",
                    printCustom2Code: "PO",
                    printCustom3Code: "INV",
                    printCustom4Code: "DP",
                }
            }else{
                optionsFlag = {
                    printCustom1Code: "TN",
                    printCustom2Code: "PO",
                    printCustom3Code: "IK",
                    printCustom4Code: "DP",
                }
            }
            this.packageList.map(item=>{
                for(let key in item.options){
                    for(let key2 in optionsFlag){
                        if(key == key2){
                            item.options[key] = optionsFlag[key2]
                        }
                    }
                }
            })
            return retuFalg;
        },
		async submit() {

			let valid = await this.validator();
            let subFalg = await this.beforeValid('submit');
            if(subFalg){
                return
            }
            // 判断清关必填
            if(!this.showPack && this.fromAddress.country!=this.toAddress.country){
                let CusTomsFalg = await this.validCustom();
                if(!CusTomsFalg){
                    return
                }else{
                    let customsInfo = {
                        currency:this.customsItems.currency,
                        value:this.customsItems.value,
                        customsItems:[this.customsItems]
                    }
                    this.packageList[0].customsInfo = customsInfo
                }
            }
			if (valid) {
				const formdata = {

					fromAddress:this.fromAddress,
					toAddress:this.toAddress,
					...this.otherData,
                    carrier:this.carrier,
                    serviceCode:this.serviceCode,
                    shipments:this.packageList,
                    returnShipment:this.replaceGoods,
                    type:0,

				};
				delete formdata.id;
				const response = await HttpCreateLabel(formdata).catch(res => {
					this.$Message.error(res.message || 'error');
				});
				if (response) {
					this.$Message.success(response.message || 'success');
					this.goRoute('label');
				}
			}
		},
        intersection(getar1, geta2, key){
            let arr = getar1.map(item=>item[key])
            let newArr3 = geta2.filter(info=>{
            return new Set(arr).has(info[key])
            })
            return newArr3
        },
        validCustom(){
            let CusTomsFalg = this.$refs['customsData'].validate();

            return CusTomsFalg

        },
		async hanldeCalculate() {

			let valid = await this.validator();
            let calFalg = await this.beforeValid('calcul');
            if(calFalg){
                return
            }
            // 判断清关必填
            if(!this.showPack && this.fromAddress.country!=this.toAddress.country){
                let CusTomsFalg = await this.validCustom();
                if(!CusTomsFalg){
                    return
                }else{
                    let customsInfo = {
                        currency:this.customsItems.currency,
                        value:this.customsItems.value,
                        customsItems:[this.customsItems]
                    }
                    this.packageList[0].customsInfo = customsInfo
                }
            }
			if (valid) {
                this.packageList.map( item =>{
                    return item.options.deliveryConfirmation = this.otherData.deliveryConfirmation

                })

                this.loading = true;
				const formdata = {
					fromAddress:this.fromAddress,
					toAddress:this.toAddress,
					...this.otherData,
                    shipments:this.packageList,
                    returnShipment:this.replaceGoods,
				};
				delete formdata.id;
				this.isCalculate = true;

                const response = await HttpCalculateLabel(formdata).catch(res => {
					this.$Message.error(res.message || 'error')
                    this.loading = false;
				});
				if (response) {
                    this.showSubmit = true;
                    let arr1 = [],arr2 = [];
                    response.data.shipments.map(item=>{
                        item.showOneTable = true;
                        arr1.push(item.rates);
                    })

                    arr2 = arr1.reduce((a, b)=>{
                        return this.intersection(a, b, 'serviceCode')
                    })
                    let arr3 = arr2.map(item=>item.serviceCode)
                    this.calculShipments = response.data.shipments;
                    this.calculShipments.map(item=>{
                        item.rates = item.rates.filter(one=>{
                            return new Set(arr3).has(one.serviceCode)
                        })
                        item.rates.map((json,index)=>{
                            json.index = index

                        })
                    })
                    this.loading = false;
					this.$Message.success(response.message || 'success');;
				}
			}
		},
	},
};
</script>

